<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ollama Chat Streaming</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 h-screen flex flex-col">

<!-- Chat Display -->
<div id="chat-container" class="flex-1 overflow-y-auto p-4 space-y-4"></div>

<!-- Input -->
<div class="p-4 bg-white flex border-t">
    <input id="user-input" type="text" placeholder="请输入消息..." class="flex-1 border rounded px-3 py-2 mr-2" />
    <button id="send-btn" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">发送</button>
</div>

<script>
    const chatContainer = document.getElementById('chat-container');
    const input = document.getElementById('user-input');
    const sendBtn = document.getElementById('send-btn');

    function appendMessage(content, role, id = null) {
        let msg = id ? document.getElementById(id) : null;
        if (!msg) {
            msg = document.createElement('div');
            msg.id = id || '';
            msg.className = role === 'user' ? 'text-right' : 'text-left text-gray-800';
            msg.innerHTML = `<div class="inline-block bg-${role === 'user' ? 'blue' : 'gray'}-200 rounded px-4 py-2 whitespace-pre-wrap">${content}</div>`;
            chatContainer.appendChild(msg);
        } else {
            msg.querySelector('div').textContent += content;
        }
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    function sendMessage() {
        const message = input.value.trim();
        if (!message) return;

        const model = 'deepseek-r1:1.5b';
        input.value = '';
        const msgId = 'msg-' + Date.now();

        appendMessage(message, 'user');
        appendMessage('', 'assistant', msgId); // 创建空消息用于后续追加内容

        // 构建 SSE 请求 URL
        const url = `http://127.0.0.1:8000/api/v1/ollama/generate_stream?model=${encodeURIComponent(model)}&message=${encodeURIComponent(message)}`;

        const eventSource = new EventSource(url);

        eventSource.onmessage = (event) => {
            try {
                // 如果返回是 JSON 格式：
                const data = JSON.parse(event.data);
                const chunk = data.results?.[0]?.output?.content || '';
                appendMessage(chunk, 'assistant', msgId);
            } catch (e) {
                // 如果是纯文本格式：
                appendMessage(event.data, 'assistant', msgId);
            }
        };

        eventSource.onerror = (err) => {
            console.error('SSE error:', err);
            eventSource.close();
        };

        eventSource.onopen = () => {
            console.log('连接已建立');
        };
    }

    sendBtn.addEventListener('click', sendMessage);
    input.addEventListener('keydown', e => {
        if (e.key === 'Enter') sendMessage();
    });
</script>

</body>
</html>
